'use strict';
const uniID = require('uni-id-common')
exports.main = async (event, context) => {
	const {
		action,
		data
	} = event;
	const uniIDIns = uniID.createInstance({ // 创建uni-id实例
		context: context,
		// config: {} // 完整uni-id配置信息，使用config.json进行配置时无需传此参数
	})
	const dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云函数的event和context，必传
			event,
			context
		})
	const myDB = dbJQL.collection('uni-id-users');
	const payload = await uniIDIns.checkToken(event.uniIdToken) // 后续使用uniIDIns调用相关接口
	const uid = payload.uid
	try {
		switch (action) {
			case 'getInviteInfo':
				return await getInviteInfo(uid);
			case 'generateInviteCode':
				return await generateInviteCode(uid);
			case 'getInviteList':
				return await getInviteList(uid, data.page, data.limit);
			case 'validateInviteCode':
				return await validateInviteCode(data.inviteCode);
			default:
				return {
					code: 404,
						message: '未知操作'
				};
		}
	} catch (error) {
		console.error('邀请码云函数错误:', error);
		return {
			code: 500,
			message: '服务器错误'
		};
	}
};

// 获取邀请信息
async function getInviteInfo(uid) {
	const userRes = await dbJQL.collection('uni-id-users').doc(uid).field('my_invite_code').get();
	console.log('userRes',userRes)
	if (userRes.data.length === 0) {
		return {
			code: 404,
			message: '用户不存在'
		};
	}

	const userData = userRes.data[0];

	// 如果没有邀请码，生成一个
	if (!userData.my_invite_code) {
		const inviteCode = await generateUniqueInviteCode();
		await dbJQL.collection('uni-id-users').doc(uid).update({
			my_invite_code: inviteCode
		});
		userData.my_invite_code = inviteCode;
	}

	return {
		code: 200,
		data: userData
	};
}

// 生成唯一邀请码
async function generateUniqueInviteCode() {
	const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	let code = '';
	let isUnique = false;

	while (!isUnique) {
		// 生成6位随机码
		for (let i = 0; i < 6; i++) {
			code += chars.charAt(Math.floor(Math.random() * chars.length));
		}

		// 检查是否已存在
		const res = await dbJQL.collection('uni-id-users').where({
			my_invite_code: code
		}).count();

		if (res.total === 0) {
			isUnique = true;
		} else {
			code = ''; // 重置，重新生成
		}
	}

	return code;
}

// 获取邀请列表
async function getInviteList(uid, page = 1, limit = 10) {
	const invitedUsers = await dbJQL.collection('uni-id-users').where({
			invited_by: uid
		}).field({
			name: true,
			create_time: true,
			department: true
		}).orderBy('create_time', 'desc')
		.skip((page - 1) * limit)
		.limit(limit)
		.get();

	const totalRes = await dbJQL.collection('uni-id-users').where({
		invited_by: uid
	}).count();

	return {
		code: 200,
		data: {
			list: invitedUsers.data,
			total: totalRes.total,
			page,
			limit
		}
	};
}

// 验证邀请码
async function validateInviteCode(inviteCode) {
	const userRes = await dbJQL.collection('uni-id-users').where({
		my_invite_code: inviteCode
	}).field({
		_id: true,
		name: true
	}).get();

	if (userRes.data.length === 0) {
		return {
			code: 404,
			message: '邀请码无效'
		};
	}

	return {
		code: 200,
		data: userRes.data[0]
	};
}